
/**
 * created by zt on 2018/04/20
 */
import React from 'react';
import {Button, Popconfirm, Popover, Icon} from 'antd';
// service 服务
import ConfigurationCenterService from 'containers/setting/configuration-center/configuration-center.service';
// 数据查询条件
import 'styles/setting/configuration-center/configuration-detail.scss';

import {connect} from 'react-redux';
import EditRule from 'containers/setting/configuration-center/configuration-detail/edit-rule';
import ConfigurationCenterModel from 'containers/setting/configuration-center/configuration-center.model';
import {messages, deepCopy} from "share/common";
import menuRoute from "routes/menuRoute";
import Condition from 'components/condition';
import {batchOperations} from "components/template/wrapped-table-params/batch-operations";
import settingService from "../../../request-and-expense-settings/request-and-expense-settings.service";
import Info from "components/info";
import AdvancedTable from 'components/advanced-table'
import SlideFrame from "components/slide-frame";
import Space from 'components/space';
import JumpConfigCenter from '../jump-config-center';

const { If } = Condition;
const { SimpleTable } = AdvancedTable;

class ConfigurationDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,  // 加载状态
      configData: [], // 数据
      query: {}, // 查询条件
      columns: [
        {title: "优先级", key: "priority", dataIndex: "priority", width: 100},
        {title: "账套", key: "SET_OF_BOOKS", dataIndex: "SET_OF_BOOKS"}
      ], // 表头
      tableData: [], // 表单内容
      showRuleDetail: false, // 显示规则详情
      title: '', // 编辑框标题
      currentRule: '', // 当前的规则
      rule: {}, // 规则格式
      configurationDetail: menuRoute.getRouteItem('configuration-center') //配置中心route
    }
  }

  infoData = (configData) => {
    return {
      dataSource: {
        explain: configData.configItem.description,
        defaultValueDesc: configData.configItem.defaultValueDesc,
        desc: messages('expense-3.key196')/*注：规则的优先级数字可重复，存在优先级数字重复的规则时，排序靠前的规则优先级更高。*/
      },
      attributes: [
        { title: messages('expense-3.key4')/*说明*/, dataIndex: 'explain', span: 24, widthFix: false},
        { title: messages('expense-3.key254')/*未命中自定义规则则按默认规则执行*/, dataIndex: 'defaultValueDesc', span: 24, widthFix: false},
        { title: '', dataIndex: 'desc', span: 24, colon: false, widthFix: false }
      ]
    }
  };

  componentWillMount() {
    this.initConfigurationQuery();
  }

  // 初始化 配置项查询值
  initConfigurationQuery = () => {
    this.setState({
      query: {
        page: 0,
        size: 1000,
        itemIds: [this.props.params.id],
        tenantId: this.props.tenantInfo.id, // 租户id
        getDetail: 'Y' // 获取配置项详情
      }
    });
  };

  service = (page, size) => {
    const {query} = this.state;
    return ConfigurationCenterService.getConfigurationList(query).then(res => {
      const configData = res.data.rows[0];
      const {columns, rule} = this.configFactorsHandle({
        configFactors: configData.configFactors,
        configItem: configData.configItem
      });
      const tableData = this.tableDataHandle({configRules: configData.configRules, configFactors: configData.configFactors, configItem: configData.configItem});
      this.setState({
        configData,
        infoData: this.infoData(res.data.rows[0]),
        columns,
        tableData,
        rule,
        loading: false,
        showRuleDetail: false
      });
      return { data: {rows: tableData, total: tableData.length} };
    });
  };

  /**
   * @description configFactors数据处理
   * @param configFactors ConfigFactors
   * @param configItem ConfigItem
   *
   * */
  configFactorsHandle = ({configFactors, configItem}) => {
    const columns = []; // 表头
    let rule = {}; // 默认规则格式
    const level = { // 优先级
      title: messages('expense-3.key69')/*优先级*/,
      key: 'priority',
      dataIndex: 'priority',
      width: 100
    };
    // 默认规则格式
    rule = deepCopy(ConfigurationCenterModel.configurationRule);
    rule.configRule.configItemId = this.props.params.id;

    columns.push(level);

    configFactors.map(item => {
      // 如果当前值为隐藏的话 表格不显示
      if (item.hide !== 'Y') {
        const tableHeadItem = {
          title: item.factorName,
          key: item.factorCode,
          dataIndex: item.factorCode
        };
        columns.push(tableHeadItem)
      }
      const ruleItem = {
        factorCode: item.factorCode,
        factorValue: null,
        factorValueDesc: null
      };
      rule.configRuleFactors.push(ruleItem);
    });
    // 校验结果
    const validateRules = {
      title: messages('expense-3.key53')/*校验结果*/,
      key: 'validateResult',
      dataIndex: 'validateResult',
      width: '20%',
      render: value => <Popover content={value}>{value}</Popover>
    };

    columns.push(validateRules);
    const ruleItem = {
      factorCode: configItem.itemCode,
      factorValue: null,
      factorValueDesc: null
    };
    rule.configRuleFactors.push(ruleItem);
    // 获取
    const actions = this.getTableActions();
    columns.push(actions);
    return {columns, rule};
  };

  /**
   * @description 获取表格操作列数据
   *
   * */
  getTableActions = () => {
    let title = messages('expense-3.key198')/*确认删除吗？*/;
    let ok = messages('common.ok')/*确定*/; // 确认删除提示文案
    let cancel = messages('common.cancel')/*取消*/; // 取消删除提示文案
    let deleteBtn = messages('common.delete')/*删除*/; // 删除按钮文案

    return {
      title: messages('common.operation')/*操作*/,
      key: 'action',
      width: 100,
      render: (rule) => (
        <Popconfirm title={title} placement="topRight" okText={ok} cancelText={cancel}
                    onConfirm={() => this.handleDeleteRule(rule)}>
          <a href="javascript:void(0);" onClick={(e) => {
            e.preventDefault();
            e.stopPropagation();
          }}>
            {deleteBtn}
          </a>
        </Popconfirm>
      )
    };
  };

  /**
   * @description 表格显示数据处理
   * @param configRules ConfigRule[]
   * @param configFactors ConfigFactor[]
   *
   * */
  tableDataHandle = ({configRules, configFactors, configItem}) => {
    const tableData = []; // 表格数据
    // 如果规则有数据 则处理规则数据
    if (Array.isArray(configRules) && configRules.length > 0) {
      configRules.map(configRule => {
        const tableItem = {
          id: configRule.configRule.id,
          priority: configRule.configRule.priority
        };
        configFactors.map(item => {
          tableItem[item.factorCode] = (configRule.configRuleFactorMap[item.factorCode] && configRule.configRuleFactorMap[item.factorCode].factorValueDesc) || '-';
        });
        // 校验结果
        if(configItem.resultType === 'DATALIST'){
          let arrays = JSON.parse(JSON.parse(JSON.stringify(configRule.configRule.valueName)));
          configRule.configRule.valueName = (
            <div>
              {
                arrays.map((item) => {
                  return(
                    <div>
                      {item.fieldLabel}：{item.valueDesc || '-'}
                    </div>
                  )
                })
              }
            </div>
          )
        }
        tableItem.validateResult = configRule.configRule.valueName;
        tableData.push(tableItem);
      })
    }
    return tableData;
  };

  /**
   *@description 添加规则
   * */
  handleAdd = () => {
    const {rule, tableData} = this.state;
    const maxLevel = tableData.length > 0 ? Math.max.apply(null, tableData.map(item => item.priority)) : 0;
    rule.configRule.priority = maxLevel + 1;

    this.setState({
      currentRule: rule,
      title: messages('common.add')/*添加*/,
      showRuleDetail: true
    });
  };

  /**
   *@description 删除规则
   *@param rule tableItem
   * */
  handleDeleteRule = (rule) => {
    ConfigurationCenterService.deleteRule(rule.id).then(() => {
      this.advancedTableRef.getList();
    });
  };

  /**
   * @description 从数据中获取当前规则数据
   * @param ruleId string
   * */
  getRuleFromData = (ruleId) => {
    const {configData} = this.state;
    const currentRule = configData.configRules.filter(item => item.configRule.id === ruleId)[0];
    return {...currentRule};
  };

  /**
   * @description 编辑规则详情
   * @param rule tableItem
   * */
  HandleViewRule = (rule) => {
    this.setState({
      currentRule: this.getRuleFromData(rule.id),
      title: messages('common.edit')/*编辑*/,
      showRuleDetail: true
    });
  };


  /**
   * @description 回退按钮
   * */
  handleBack = () => {
    this.context.router.goBack();
  };

  handleSave = () => {
    this.advancedTableRef.getList();
  };

  render() {
    const {loading, configData, columns, showRuleDetail, title, currentRule, infoData} = this.state;
    let tableParams = window.location.href.indexOf('expense-setting') > -1 ? batchOperations({
      rowKey: 'id',
      hideDefaultSelections: false,
      hideSelectAll: true
    }, [{
      type: 'DELETE',
      service: settingService.batchDeleteExpenseControl,
      onOk: () => this.advancedTableRef.getList()
    }], this) : {};
    return (
      <div className="configuration-center-detail">
        <SimpleTable
          loading={loading}
          rowKey='id'
          columns={columns}
          service={this.service}
          onRef={ref => this.advancedTableRef = ref}
          onRow={rule => ({onClick: () => this.HandleViewRule(rule)})}
          pagination={null}
          {...tableParams}
        >
          <Space size={'middle'} direction={'vertical'}>
            {infoData && (
              <Info
                loading={false}
                title={`${configData.configItem.itemName}${messages('expense-3.key199')/*规则配置*/}`}
                dataSource={infoData.dataSource}
                attributes={infoData.attributes}
                paragraph
              >
                {infoData.more}
              </Info>
            )}
            <Button type="primary" onClick={this.handleAdd}>
              {messages('common.create')/*新建*/}
            </Button>
          </Space>
        </SimpleTable>
        <If value={window.location.href.indexOf('expense-setting') === -1 && window.location.href.indexOf('invoice-management-control') === -1}>
          <a style={{ fontSize: '14px', paddingBottom: '20px' }} onClick={this.handleBack}>
            <Icon type="rollback" style={{ marginRight: '5px' }}/>{messages('common.back')/*返回*/}
          </a>
        </If>
        <SlideFrame
          width={800}
          show={showRuleDetail}
          title={title}
          hasFooter={true}
          hasMask={true}
          params={{
            currentRule,
            configItem: configData.configItem,
            configFactors: configData.configFactors,
            showRuleDetail,
            handleSave: () => this.handleSave()
          }}
          content={EditRule}
          onClose={() => this.setState({showRuleDetail: false})}
          afterClose={() => this.setState({showRuleDetail: false})}
        />
      </div>
    )
  }
}

ConfigurationDetail.contextTypes = {
  router: React.PropTypes.object
};

function

mapStateToProps(state) {
  return {
    tenantInfo: state.login.tenant
  }
}

export default connect(mapStateToProps)(ConfigurationDetail);
